import utilService from '../service/utilService'
import appService from '../service/appService'

$('.JS-download-app').click(function() {
    utilService.hideModel('reg-success-model');
    downloadApp();
    // window.location.href = utilService.getUserAgent() == "IOS" ? constant.H5_index_url : constant.Android_apk;
})

$('.JS-wait-iosApp-close').click(function() {
    utilService.hideModel('JS-wait-iosApp');
})

function downloadApp(options = {}) {
    options.iosAppName = options.iosAppName ? options.iosAppName : "gu100IOS";
    options.androidAppName = options.androidAppName ? options.androidAppName : "gu100APK";
    
    let isWechatBrowser = navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger";
    if (utilService.getUserAgent() == "IOS") {
        utilService.showModel('JS-wait-iosApp');
        return;
    }
    if (isWechatBrowser) {
        // 微信浏览器界面
        $(".JS-download-app-wx-mask").show();
    } else {
        let name = getAppName.call(options);
        appService.getAppVersion(name).then(data => {
            if (data.version && data.version.downloadUrl)
                window.location.href = data.version.downloadUrl;
        }, err => {
            console.log(err);
        })
    }
}

function getAppName() {
    return utilService.getUserAgent() == "IOS" ? parmasToObj().appname || this.iosAppName : parmasToObj().appname || this.androidAppName;
}

function parmasToObj() {
    let url = window.location.search;
    let params = url.length > 0 ? url.substr(1) : "";
    let args = {};
    let pArr = params.length ? params.split("&") : [];
    for (var i = 0; i < pArr.length; i++) {
        let item = pArr[i].split("=");
        let name = decodeURIComponent(item[0]);
        let value = decodeURIComponent(item[1]);
        if (name.length > 0) {
            args[name] = value;
        }
    }
    return args;
}